angular.module('starter.services', [])

.service('LoginService', function($q) {
    return {
        loginUser: function(name, pw) {
            var deferred = $q.defer();
            var promise = deferred.promise;

            if (login(name, pw)) {
                deferred.resolve('Welcome ' + name + '!');
            } else {
                deferred.reject('Wrong credentials.');
            }
            promise.success = function(fn) {
                promise.then(fn);
                return promise;
            }
            promise.error = function(fn) {
                promise.then(null, fn);
                return promise;
            }
            return promise;
        }
    }
});


function login(email, password) {
    var dUID = device.uuid;
    var ret = false;
    jQuery.ajax({
            type: "POST",
            url: "http://ba.tech-time.de/kurier/json.php",
            //data: {action:"login",sessionDeviceId:dUID,userEmail:email,userPassword:password}, 
            data: {
                action: "login",
                sessionDeviceId: dUID,
                userEmail: "nico.schmidt4@gmx.de",
                userPassword: "123456"
            },
            async: false
        })
        .done(function(data) {
            var obj = jQuery.parseJSON(data);

            if (obj.errorcode == "0") {
                toLocalStorage("sessionID", obj.sessionId);
                toLocalStorage("sessionUId", obj.sessionUId);
                ret = true;
            }

        });
    return ret;
}

function toLocalStorage(key, value) {
    window.localStorage.setItem(key, value);
}

function fromLocalStorage(key) {
    return window.localStorage.getItem(key);
}
